<template>
  <div class="practice-view">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>个性化练习</span>
          <el-select
            v-model="selectedSubject"
            clearable
            placeholder="请选择科目"
            style="width: 160px"
            @change="fetchQuestions"
          >
            <el-option
              v-for="subject in subjects"
              :key="subject"
              :label="subject"
              :value="subject"
            />
          </el-select>

          <el-button
            :disabled="!selectedSubject"
            :loading="loading"
            type="primary"
            @click="fetchQuestions"
          >
            换一批
          </el-button>
        </div>
      </template>

      <div v-if="loading">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="questions.length > 0">
        <div
          v-for="(question, index) in questions"
          :key="question.questionId"
          class="question-item"
        >
          <p
            v-if="question && question.content"
            v-html="renderMarkdown(`${index + 1}. ${question.content}`)"
          ></p>

          <template v-if="question.type === 'SINGLE_CHOICE'">
            <el-radio-group v-model="answers[question.questionId]">
              <el-radio
                v-for="(option, key) in safeParseOptions(question.options)"
                :key="key"
                :label="key"
              >
                <span v-html="renderMarkdown(`${key}. ${option}`)"></span>
              </el-radio>
            </el-radio-group>
          </template>

          <template v-else-if="question.type === 'MULTIPLE_CHOICE'">
            <el-checkbox-group v-model="multiAnswers[question.questionId]">
              <el-checkbox
                v-for="(option, key) in safeParseOptions(question.options)"
                :key="key"
                :label="key"
              >
                <span v-html="renderMarkdown(`${key}. ${option}`)"></span>
              </el-checkbox>
            </el-checkbox-group>
          </template>

          <template v-else-if="['SUBJECTIVE', 'FILL_IN_BLANK'].includes(question.type)">
            <el-upload
              :action="uploadUrl"
              :limit="1"
              :on-success="(res) => handleUploadSuccess(question.questionId, res)"
              :show-file-list="false"
              accept="image/*"
            >
              <el-button size="small">上传图片回答</el-button>
              <span v-if="uploadImages[question.questionId]">已上传</span>
            </el-upload>
          </template>

          <el-button size="small" style="margin-left: 20px" @click="submitAnswer(question)">
            提交答案
          </el-button>
        </div>
      </div>

      <el-empty v-else description="暂时没有推荐的题目" />
    </el-card>

    <el-dialog v-model="feedbackVisible" title="答案反馈">
      <div v-if="feedbackData">
        <el-alert
          :closable="false"
          :title="feedbackData.correct ? '回答正确！' : '回答错误'"
          :type="feedbackData.correct ? 'success' : 'error'"
          show-icon
        />
        <div v-if="!feedbackData.correct" class="feedback-content">
          <p><strong>正确答案:</strong> {{ formatCorrectAnswer(feedbackData.correctAnswer) }}</p>
          <p><strong>题目解析:</strong></p>
          <div v-html="renderMarkdown(feedbackData.analysis)" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { apiClient, handleErrorAndRedirect } from '@/api'
import { renderMarkdown } from '@/api/utils.ts'

const selectedSubject = ref<string | null>(null)
const subjects = ['语文', '数学', '英语', '物理', '化学', '生物', '历史', '地理', '政治']
const questions = ref<any[]>([])
const loading = ref(false)
const answers = reactive<Record<number, string>>({})
const multiAnswers = reactive<Record<number, string[]>>({})
const uploadImages = reactive<Record<number, string>>({})
const feedbackVisible = ref(false)
const feedbackData = ref<any>(null)
const uploadUrl = '/file/upload'

const fetchQuestions = async () => {
  if (!selectedSubject.value) return
  loading.value = true
  try {
    const response = await apiClient.get('/practice/questions', {
      params: { count: 5, subject: selectedSubject.value },
    })
    questions.value = Array.isArray(response.data) ? response.data : []
  } catch (error) {
    handleErrorAndRedirect(error, '获取练习题失败')
    questions.value = []
  } finally {
    loading.value = false
  }
}

const safeParseOptions = (optionsStr: string): Record<string, string> => {
  try {
    const parsed = JSON.parse(optionsStr)
    return parsed && typeof parsed === 'object' ? parsed : {}
  } catch {
    return {}
  }
}

const formatCorrectAnswer = (answerStr: string) => {
  try {
    const parsed = JSON.parse(answerStr)
    return Array.isArray(parsed.correct) ? parsed.correct.join(', ') : parsed.correct
  } catch {
    return '解析失败'
  }
}

const handleUploadSuccess = (questionId: number, res: any) => {
  if (res && res.url) uploadImages[questionId] = res.url
}

const submitAnswer = async (question: any) => {
  const id = question.questionId
  let userAnswer

  if (question.type === 'SINGLE_CHOICE') {
    userAnswer = { correct: answers[id] }
  } else if (question.type === 'MULTIPLE_CHOICE') {
    userAnswer = { correct: multiAnswers[id] || [] }
  } else if (['SHORT_ANSWER', 'FILL_IN_BLANK'].includes(question.type)) {
    if (!uploadImages[id]) {
      ElMessage.warning('请上传图片作为答案')
      return
    }
    userAnswer = { image: uploadImages[id] }
  }

  try {
    const res = await apiClient.post(`/practice/questions/${id}/submit`, {
      userAnswer: JSON.stringify(userAnswer),
    })
    feedbackData.value = res.data
    feedbackVisible.value = true
  } catch (error) {
    ElMessage.error('提交答案失败')
  }
}
</script>

<style scoped>
.practice-view {
  padding: 20px;
}

.card-header {
  display: flex;
  gap: 12px;
  align-items: center;
}

.question-item {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.feedback-content {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}
</style>
